package com.hxgis.oc.cma;

import com.hxgis.oc.cma.util.*;
import com.hxgis.oc.config.OConfig;
import com.hxgis.oc.product.file.DownloadTask;
import com.hxgis.oc.product.geojson.GeojsonConvTask;
import com.hxgis.oc.product.idw.IDWConvTask;
import com.hxgis.oc.util.TimerBase;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
public class CmaTimer1h extends TimerBase {
    public static void start(CmaElementRequest request) {
        TimerBase.start(CmaTimer1h.class.getSimpleName(),new CmaTimer1h(request));
    }

    public CmaTimer1h(CmaElementRequest req){
        super(req.getDataTable(),1,0);
        request = req;
        isUTC = true;
    }

    protected CmaElementRequest request;

    @Override
    protected DownloadTask createATask(long fid, File outputFile){
        DownloadTask task = new DownloadTask(fid, dataSet, outputFile);

        GeojsonConvTask convTask1 = new GeojsonConvTask(fid, dataSet);
        convTask1.setConvFunc(t-> SurfEleRequest.createGeojsonProduct(t));

        IDWConvTask convTask2 = new IDWConvTask(fid, dataSet);
        convTask2.setConvFunc(t-> SurfEleRequest.createIDWProduct(t));

        task.addConvertTask(convTask1);
        task.addConvertTask(convTask2);
        return task;
    }

    List<LocalDateTime> genQueryTimes(){
        List<LocalDateTime> generateTimes = new ArrayList<>();

        for(int i=0;i<24;i++){
            LocalDateTime queryTime = timeToday00.plusHours(i);
            if(queryTime.isAfter(timeCurrent)){
                break;
            }
            generateTimes.add(queryTime);
        }

        //当前小时等下个小时才下载
        if(!generateTimes.isEmpty()){
            generateTimes.remove(generateTimes.size() - 1);
        }

        return generateTimes;
    }

    @Override
    public void run() {
        updateTime();

        if(!isTimeToUpdate()){
            return;
        }

        List<LocalDateTime> queryTimes = genQueryTimes();

        if(queryTimes.isEmpty()){
            return;
        }

        LocalDateTime startDataTime = queryTimes.get(0);

        long fileCount = fileProductManager.count(dataSet,startDataTime);

        if(queryTimes.size() == fileCount)
        {
            return;
        }

        long taskCount = 0;
        for(LocalDateTime time : queryTimes)
        {
            long fid =  OConfig.genTimeStampFid(time);
            File file = fileProductManager.getFile(dataSet,String.format("%d.json",fid));
            String url = request.generateQueryUrl(time);
            DownloadTask task = createATask(fid,file);
            task.setUrl(url);

            if(!fileProductManager.exist(dataSet,fid)){
                fileProductManager.getWorker().addTask(task);
                taskCount++;
            }
        }

        log.info("[{} {}至现在] :已下载{} 队列{}", dataSet,OConfig.formatLogString(startDataTime,isUTC),fileCount,taskCount);
    }
}
